/*
 * Syntelos 'SX'
 * Copyright (C) 1998, 2007  John Pritchard.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 */
package syntelos.sx.methods.s;

import syntelos.sx.Response;
import syntelos.sx.Request;
import syntelos.sys.Capabilities;

import alto.sec.DN;
import alto.sec.Keys;
import alto.sec.pkcs.PKCS12;
import alto.sec.x509.AVA;
import alto.sec.x509.AVAKeyword;
import alto.sec.x509.X500Name;
import alto.sec.x509.X509Certificate;

import alto.io.Authentication;
import alto.io.Input;
import alto.io.Output;
import alto.io.Principal;
import alto.io.Uri;
import alto.lang.Buffer;
import alto.lang.Component;
import alto.lang.InputStream;
import alto.lang.Type;
import alto.sys.FileManager;
import alto.sys.Reference;

/**
 * Authenticate as 'role' for path to '/s/{UID}' (with or without any
 * fext) to assign 'role' to 'UID'.
 * 
 * @see alto.io.Authentication#NotApp
 * @see syntelos.sys.Capabilities$RoleWrite
 * @since 1.6
 */
public class Role
    extends Abstract
{

    public Role(){
        super();
    }


    public void respond(Request req)
        throws java.io.IOException,
               java.lang.InterruptedException
    {
        super.respond(req);
        if (this.isAuthenticated(Authentication.NotApp,Capabilities.RoleWrite.Instance)){
            Principal.Actual role = (Principal.Actual)req.getPrincipal();

            String userId = IdentifierFor(req);
            if (null != userId){
                Keys user = Keys.Tools.Dereference(userId);
                if (null != user){
                    if (user.addRole(role)){
                        user.writeMessage();
                        this.setStatusOk();
                    }
                    else
                        this.setStatusNoContent();
                }
                else
                    this.setStatusNotFound();
            }
            else
                this.setStatusBadRequest();
        }
        else
            this.setStatusUnauthorized();
    }
}
